import { useEffect, useRef } from "react";
import { getTargetElement } from "./get-target-element";

/**
 * mutation observer hook
 * @param {*} callback
 * @param {*} target
 * @param {*} options
 */
const useMutationObserver = (callback: any, target: any, options = {}) => {
  const callbackRef = useRef(callback);

  useEffect(() => {
    const element = getTargetElement(target);
    let observer;
    if (element) {
      observer = new MutationObserver(callbackRef.current);
      observer?.observe?.(element, options);
    }
    return () => {
      if (observer) {
        observer?.disconnect?.();
      }
    };
  }, [target]);
};

export { useMutationObserver };
